layui.use('table', function () {
    var table = layui.table;
    //第一个实例
    table.render({
        elem: '#demo'
        , url: '/findTeacher' //数据接口
        , method: 'post'
        , page: true //开启分页
        , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
        , limit: 7
        , id:'testReload'
        , limits: [3, 5, 7]
        , cols: [[
            { field: 'pkId',width: 80, type: 'checkbox' },
            { field: 'gradeId', width: 180, title: '班级ID', sort: true,hide:true},
            { field: 'gradeName', width: 180, title: '班级名称', sort: true},
            { field: 'classRemark', width: 180,title: '班级描述', sort: true,},
            { field: 'studentsNumber', width: 180,title: '班级人数' },
            { field: 'teacherName', width: 180,title: '班主任' },
            { field: 'lectureName', width: 180,title: '讲师' , },
            { field: 'classroomClassroomId', width: 180,title: '所在教室', sort: true },
            { field: 'createdate', width: 200,title: '创建时间', sort: true },
            { field: 'updatedate', width: 200,title: '修改时间', sort: true },
            { field: 'right', width: 140, title: '操作', toolbar: '#barDemo' },
        ]],
        done: function(res, curr, count) {
            $("[data-field='classRemark']").children().each(function () {
                if ($(this).text() == 'true') {
                    $(this).text('班级已成立');
                } else if ($(this).text() == 'false') {
                    $(this).text('班级未成立');
                }
            });
            $("[data-field='classroomClassroomId']").children().each(function () {
                if ($(this).text() == '10000') {
                    $(this).text('405室');
                } else if ($(this).text() == '10001') {
                    $(this).text('211阶梯教室');
                }else if ($(this).text() == '10002') {
                    $(this).text('东教');
                }else if ($(this).text() == '10003') {
                    $(this).text('西教');
                }else if ($(this).text() == '10004') {
                    $(this).text('北教');
                }else if ($(this).text() == '10005') {
                    $(this).text('南教');
                }else if ($(this).text() == '10006') {
                    $(this).text('201阶梯教室');
                }else if ($(this).text() == '10007') {
                    $(this).text('215阶梯教室');
                }else if ($(this).text() == '10008') {
                    $(this).text('305阶梯教室');
                }else if ($(this).text() == '10009') {
                    $(this).text('123教室');
                }else if ($(this).text() == '10010') {
                    $(this).text('1213教室');
                }else if ($(this).text() == '10011') {
                    $(this).text('2111阶梯教室');
                }else if ($(this).text() == '10012') {
                    $(this).text('438阶梯教室');
                }
            });
        },
        parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": res.data //解析数据列表
            };
        },
        request: {
            pageName: 'page' // 页码的参数名称，默认：page
            , limitName: 'limit' //每页数据量的参数名，默认：limit
        },
    });
    //升序降序后重新渲染
    table.on('sort(test)', function(obj) {
        table.reload('testReload', {
            initSort: obj
        });
    });
    table.reload('testReload', {});
    //表单数据重载
    var $ = layui.$,active = {
        reload: function(){
            var gradeName=$("#gradeName");
            var teacherName=$("#classTeacherName");
            var lectureName=$("#lecturerName");
            //执行重载
            table.reload('testReload', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where: {
                    gradeName: gradeName.val(),
                    teacherName: teacherName.val(),
                    lectureName: lectureName.val(),
                }
            });
        }
    };
    $('.demoTable .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
    //监听头工具事件
    table.on('toolbar(test)',function (obj){
        var checkStatus = table.checkStatus(obj.config.id)
            ,data = checkStatus.data //获取选中的数据
            ,delList=[];
        for(var i=0;i<data.length;i++){
            delList.push(data[i].pkId);
        }
        var json={"pkIds":delList};

        switch(obj.event){
            case 'add':
                layer.msg('添加');
                layer.open({
                    type: 1 //此处以iframe举例
                    , title:'教师信息录入表'
                    , area: ['800px', '650px']
                    , shade: 0
                    , maxmin: true
                    ,content:$("#insertPage")
                })
                //班级下拉框
                $.ajax({
                    type:"post",
                    url:"/classroomId",
                    contentType: "application/json;charset=utf-8",
                    dataType:"json",
                    success:function (classroom) {
                        var $classrooms = "<option value=''>请选择</option>";
                        for (var i = 0; i < classroom.length; i++) {

                            $classrooms += "<option value=" + classroom[i].classroomId + ">" + classroom[i].classroomName + "</option>"

                        }
                        $("select[name='itsclassroomClassroomId']").html($classrooms);
                        $("select[name='itsclassroomClassroomId']").val(classroom.classroomId);
                    },error:function (){
                        layer.msg("请求失败");
                    }
                })
                //班主任下拉框
                $.ajax({
                    type:"post",
                    url:"/itsclassTeacherName",
                    contentType: "application/json;charset=utf-8",
                    dataType:"json",
                    success:function (teacherName) {

                        var $teacherNames = "<option value=''>请选择班主任</option>";
                        for (var i = 0; i < teacherName.length; i++) {


                            $teacherNames += "<option value=" + teacherName[i].teacherId + ">" + teacherName[i].teacherName + "</option>"

                        }
                        $("select[name='itsclassTeacherId']").html($teacherNames);
                        $("select[name='itsclassTeacherId']").val(data.classTeacherId);
                    },error:function (){
                        layer.msg("请求失败");
                    }
                })
                //讲师下拉框
                $.ajax({
                    type:"post",
                    url:"/itsjiangshi",
                    contentType: "application/json;charset=utf-8",
                    dataType:"json",
                    success:function (teacherName) {

                        var $teacherNames = "<option value=''>请选择讲师</option>";
                        for (var i = 0; i < teacherName.length; i++) {


                            $teacherNames += "<option value=" + teacherName[i].lectureId + ">" + teacherName[i].lectureName + "</option>"

                        }
                        $("select[name='itslecturerId']").html($teacherNames);
                        $("select[name='itslecturerId']").val(data.lecturerId);
                    },error:function (){
                        layer.msg("请求失败");
                    }
                })
                $("#insertTeacher").click(function (){
                    var istData={
                        "gradeName":$("#itsgradeName").val(),
                        "classTeacherId":$("#itsclassTeacherId").val(),
                        "classTeacherName":$("#itsclassTeacherName").val(),
                        "lecturerId":$("#itslecturerId").val(),
                        "lecturerName":$("#itslecturerName").val(),
                        "studentsNumber":$("#itsstudentsNumber").val(),
                        "classroomClassroomId":$("#itsclassroomClassroomId").val(),
                        "classRemark":$("#itsclassRemark").val(),
                    }


                    $.ajax({
                        type:"post",
                        url:"/insertTeacher",
                        data:JSON.stringify(istData),
                        contentType: "application/json;charset=utf-8",
                        dataType:"json",
                        success:function (istData) {
                            if(istData=='1'){
                                layer.msg('添加成功',{icon:6,time:1000},function () {
                                    window.location.reload();
                                })
                            }else if(istData=='0'){
                                layer.msg('添加失败',{icon:5,time:1000},function () {
                                    window.location.reload();
                                })
                            }
                        },error:function (error) {
                            layer.msg("添加请求失败")
                        }
                    });
                })
                break;
            case 'update':
                if(data.length === 0){
                    layer.msg('请选择一行');
                } else if(data.length > 1){
                    layer.msg('只能同时编辑一个');
                } else {
                    layer.alert('编辑 [id]：'+ checkStatus.data[0].id);
                }
                break;
            case 'delete':
                if(data.length === 0){
                    layer.msg('请选择一行');
                } else {
                    layer.msg('删除');
                    $.ajax({                //批量删除
                        type:"post",
                        url:"/deleteTeacherList",
                        contentType: "application/json;charset=utf-8",
                        data:JSON.stringify(json),
                        dataType:"json",
                        success:function (delData) {
                            if(delData > 0){
                                layer.msg('删除成功',{icon:6,time:1000},function () {
                                    window.location.reload();
                                })
                            }else if(delData < 1) {
                                layer.msg('删除失败', {icon: 5, time: 1000}, function () {
                                    window.location.reload();
                                })
                            }
                        },error:function (error) {
                            layer.msg("删除请求失败");
                        }
                    })
                }
                break;
        };
    });
    //监听行工具事件
    table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event //获得 lay-event 对应的值
            ,dropdown=layui.dropdown;
        if(layEvent === 'detail') {
            layer.msg('查看操作');
            layer.open({
                type: 1 //此处以iframe举例
                , title: data.gradeName + '班详细信息'
                , area: ['800px', '600px']
                , shade: 0
                , maxmin: true
                , content: $("#detailedInformation")
                , success: function (layero, index) {

                    //数据回显
                    $("#infoGradeId").val(data.gradeName);
                    $("#infoClassTeacherName").val(data.teacherName);
                    $("#infolecturerId").val(data.lectureName);
                    $("#infoStudentsNumber").val(data.studentsNumber);
                    $("#infoclassRemark").val(data.classRemark);
                    $("#gradeId").val(data.gradeId);
                    $.ajax({
                        type:"post",
                        url:"/classroomId",
                        contentType: "application/json;charset=utf-8",
                        dataType:"json",
                        success:function (classroom) {
                            var $classrooms = "<option value='' style='width: 1200px'>请选择</option>";
                            for (var i = 0; i < classroom.length; i++) {

                                $classrooms += "<option value=" + classroom[i].classroomId + ">" + classroom[i].classroomName + "</option>"

                            }
                            $("select[name='upclassroomClassroomId']").html($classrooms);
                            $("select[name='upclassroomClassroomId']").val(data.classroomClassroomId);
                        },error:function (){
                            layer.msg("请求失败");
                        }
                    })
                    $("#insertStudent").click(function () {

                        let pkId = data.pkId

                        layer.open({
                            type: 2
                            , title: '班级添加学生页面'
                            , area: ['1650px', '700px']
                            , shade: 0
                            , maxmin: true
                            , content: "/gradeFind/" + pkId
                            , success: function (layero, index) {

                            }, end: function () {

                            }


                        })
                    })
                    $("#seeStudent").click(function () {

                        let pkId = data.pkId

                        layer.open({
                            type: 2
                            , title: '班级添加学生页面'
                            , area: ['1550px', '700px']
                            , shade: 0
                            , maxmin: true
                            , content: "/grade/" + pkId
                            , success: function (layero, index) {

                            }, end: function () {

                            }


                        })
                    })
                }, end: function () {

                }
            })
        } else if(layEvent === 'more'){
            //下拉菜单
            dropdown.render({
                elem: this //触发事件的 DOM 对象
                ,show: true //外部事件触发即显示
                ,data: [{
                    title: '编辑'
                    ,id: 'edit'
                },{
                    title: '删除'
                    ,id: 'del'
                }]
                ,click: function(menudata){
                    if(menudata.id === 'del'){
                        layer.confirm('真的删除行么', function(index){
                            obj.del(); //删除对应行（tr）的DOM结构
                            //layer.close(index);
                            //向服务端发送删除指令
                            $.ajax({
                                type:'post',
                                url:"/teacherDelete",
                                data:JSON.stringify(data),
                                contentType:'application/json;charset=utf-8',
                                dataType:"json",
                                success:function (data) {
                                    if(data=='1'){
                                        layer.msg('删除成功',{icon:6,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }else if(data=='0'){
                                        layer.msg('删除失败',{icon:5,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }
                                },error:function (error) {
                                    alert("请求失败")
                                }
                            })
                        });
                    } else if(menudata.id === 'edit'){
                        layer.msg('编辑操作，当前行 ID:'+ data.pkId);
                        layer.open({
                            type: 1 //此处以iframe举例
                            , title:'班级'+data.gradeName+'的信息'
                            , area: ['800px', '600px']
                            , shade: 0
                            , maxmin: true
                            ,content:$("#updatePage")
                        })
                        //数据回显
                        $("#upgradeName").val(data.gradeName);
                        $("#upclassTeacherId").val(data.classTeacherId);

                        $("#uplecturerId").val(data.lecturerId);
                        $("#upclassroomClassroomId").val(data.upclassroomClassroomId)

                        $("#upstudentsNumber").val(data.studentsNumber);
                        $("#upclassRemark").val(data.classRemark);
                        $.ajax({
                            type:"post",
                            url:"/classroomId",
                            contentType: "application/json;charset=utf-8",
                            dataType:"json",
                            success:function (classroom) {
                                var $classrooms = "<option value='' style='width: 1200px'>请选择</option>";
                                for (var i = 0; i < classroom.length; i++) {

                                    $classrooms += "<option value=" + classroom[i].classroomId + ">" + classroom[i].classroomName + "</option>"

                                }
                                $("select[name='upclassroomClassroomId']").html($classrooms);
                                $("select[name='upclassroomClassroomId']").val(data.classroomClassroomId);
                            },error:function (){
                                layer.msg("请求失败");
                            }
                        })
                        //班主任下拉框
                        $.ajax({
                            type:"post",
                            url:"/itsclassTeacherName",
                            contentType: "application/json;charset=utf-8",
                            dataType:"json",
                            success:function (teacherName) {

                                var $teacherNames = "<option value=''>请选择班主任</option>";
                                for (var i = 0; i < teacherName.length; i++) {


                                    $teacherNames += "<option value=" + teacherName[i].teacherId + ">" + teacherName[i].teacherName + "</option>"

                                }
                                $("select[name='upclassTeacherId']").html($teacherNames);
                                $("select[name='upclassTeacherId']").val(data.classTeacherId);
                            },error:function (){
                                layer.msg("请求失败");
                            }
                        })
                        //讲师下拉框
                        $.ajax({
                            type:"post",
                            url:"/itsjiangshi",
                            contentType: "application/json;charset=utf-8",
                            dataType:"json",
                            success:function (teacherName) {

                                var $teacherNames = "<option value=''>请选择</option>";
                                for (var i = 0; i < teacherName.length; i++) {


                                    $teacherNames += "<option value=" + teacherName[i].lectureId + ">" + teacherName[i].lectureName + "</option>"

                                }
                                console.log("dadadadad:$teacherNames")
                                $("select[name='uplecturerId']").html($teacherNames);
                                $("select[name='uplecturerId']").val(data.lecturerId);
                            },error:function (){
                                layer.msg("请求失败");
                            }
                        })
                        $("#updDetailAddr").val(data.detailAddr);//详细信息

                        $("#updateTeacher").click(function () {
                            var updData={
                                "pkId":data.pkId,
                                "gradeName":$("#upgradeName").val(),
                                "classTeacherId":$("#upclassTeacherId").val(),
                                "classTeacherName":$("#upclassTeacherName").val(),
                                "lecturerId":$("#uplecturerId").val(),
                                "lecturerName":$("#uplecturerName").val(),
                                "studentsNumber":$("#upstudentsNumber").val(),
                                "classRemark":$("#upclassRemark").val(),
                                "classroomClassroomId":$("select[name='upclassroomClassroomId']").val(),
                                "oldclassroomClassroomId":data.classroomClassroomId
                            }
                            $.ajax({
                                type:"post",
                                url:"/updateTeacher",
                                data:JSON.stringify(updData),
                                contentType: "application/json;charset=utf-8",
                                dataType:"json",
                                success:function (upddata) {
                                    if(upddata=='1'){
                                        layer.msg('修改成功',{icon:6,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }else if(upddata=='0'){
                                        layer.msg('修改失败',{icon:5,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }
                                },error:function (error) {
                                    layer.msg("修改请求失败")
                                }

                            })
                        })


                    }
                }
                ,align: 'right' //右对齐弹出（v2.6.8 新增）
                ,style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
            })
        }
    });
});